package com.ruoyi.course.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.classes.domain.Classes;
import com.ruoyi.classes.service.IClassesService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.course.domain.Course;
import com.ruoyi.course.domain.StudentAndCourse;
import com.ruoyi.course.mapper.CourseMapper;
import com.ruoyi.course.service.ICourseService;
import com.ruoyi.monitor.domain.Monitor;
import com.ruoyi.student.domain.Student;
import com.ruoyi.student.service.IStudentService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.Validator;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 课程列表Service业务层处理
 *
 * @author ruoyi
 * @date 2024-10-17
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course>
        implements ICourseService {
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);
    @Autowired
    protected Validator validator;
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IStudentService studentService;
    @Autowired
    private IClassesService classesService;

    /**
     * 查询课程列表
     *
     * @param id 课程列表主键
     * @return 课程列表
     */
    @Override
    public Course selectCourseById(Long id) {
        return courseMapper.selectCourseById(id);
    }

    /**
     * 查询课程列表列表
     *
     * @param course 课程列表
     * @return 课程列表
     */
    @Override
    public List<Course> selectCourseList(Course course) {
        return courseMapper.selectCourseList(course);
    }

    /**
     * 新增课程列表
     *
     * @param course 课程列表
     * @return 结果
     */
    @Override
    public int insertCourse(Course course) {
        course.setCreateTime(DateUtils.getNowDate());
        return courseMapper.insertCourse(course);
    }

    /**
     * 修改课程列表
     *
     * @param course 课程列表
     * @return 结果
     */
    @Override
    public int updateCourse(Course course) {
        course.setUpdateTime(DateUtils.getNowDate());
        return courseMapper.updateCourse(course);
    }

    /**
     * 批量删除课程列表
     *
     * @param ids 需要删除的课程列表主键
     * @return 结果
     */
    @Override
    public int deleteCourseByIds(Long[] ids) {
        return courseMapper.deleteCourseByIds(ids);
    }

    /**
     * 删除课程列表信息
     *
     * @param id 课程列表主键
     * @return 结果
     */
    @Override
    public int deleteCourseById(Long id) {
        return courseMapper.deleteCourseById(id);
    }

    /**
     * 导入课程数据
     *
     * @param courseList      课程列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importCourse(List<Course> courseList, Boolean isUpdateSupport, String operName) {

        if (StringUtils.isNull(courseList) || courseList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (Course course : courseList) {
            try {
                // 验证是否存在这个用户
                Course c = courseMapper.selectCourseById(course.getId());
                if (StringUtils.isNull(c)) {
                    BeanValidators.validateWithException(validator, course);
                    course.setCreateBy(operName);
                    courseMapper.insertCourse(course);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、课程 " + course.getCourseName() + " 导入成功");
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, course);
                    course.setId(c.getId());
                    course.setUpdateBy(operName);
                    courseMapper.updateCourse(course);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、课程 " + course.getCourseName() + " 更新成功");
                } else {
                    System.out.println(3);
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、课程 " + course.getCourseName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、课程 " + course.getCourseName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 获取当日学生课程
     *
     * @param id
     * @return
     */
    @Override
    public List<StudentAndCourse> getTodayCourse(Long id) {
        List<StudentAndCourse> sacl = new ArrayList<>();

//        查询家长信息
        SysUser sysUser = sysUserService.selectUserById(id);

//        获取家长的所有孩子信息
        List<Student> studentList = studentService.list(new LambdaQueryWrapper<Student>()
                .eq(Student::getStuPatriarchName, sysUser.getRealName())
                .eq(Student::getStuPatriarchPhone, sysUser.getPhonenumber()));

        for (Student student : studentList) {
//            获取当前孩子所在班级
            Classes classes = classesService.getOne(new LambdaQueryWrapper<Classes>()
                    .eq(Classes::getClassName, student.getStuClass()));

//            获取当前孩子今日课程并顺序排序
            LocalDate now = LocalDate.now();
            String dayOfWeek = String.valueOf(now.getDayOfWeek().getValue());

            List<Course> courseList = list(new LambdaQueryWrapper<Course>()
                    .eq(Course::getCourseClass, classes.getClassName())
                    .eq(Course::getCourseSchool, classes.getClassBelonging())
                    .like(Course::getCourseWeek, dayOfWeek)
                    .orderByAsc(Course::getCourseHour))
                    .stream()
                    .filter(this::isExpireToday)
                    .toList();

            sacl.add(new StudentAndCourse(student.getStuName(), courseList));
        }
        return sacl;
    }

    /**
     * 获取当前时间有效课程
     *
     * @param monitor
     * @return
     */
    @Override
    public Course getNowCourse(Monitor monitor) {
        System.out.println(monitor);
        LocalDate now = LocalDate.now();
        String dayOfWeek = String.valueOf(now.getDayOfWeek().getValue());

        List<Course> list = courseMapper.selectList(new LambdaQueryWrapper<Course>()
                        .eq(Course::getCourseClass, monitor.getClassName())
                        .eq(Course::getCourseSchool, monitor.getSchoolName())
                        .like(Course::getCourseWeek, dayOfWeek))
                .stream()
                .filter(this::isExpireNow)
                .toList();

        System.out.println("list");
        System.out.println(list);
        if (list.isEmpty()) {
            return null;
        } else {
            return list.get(0);
        }
    }

    /**
     * 判断当前时间是否在课程时间内
     *
     * @param course
     * @return
     */
    @Override
    public Boolean isExpireNow(Course course) {
        List<LocalDateTime> hourList = parseTime(course.getCourseHour(), "-", "HH:mm");
        LocalDateTime now = LocalDateTime.now();

        if (isExpireToday(course)) {
            return now.isAfter(hourList.get(0)) && now.isBefore(hourList.get(1));
        }
        return false;
    }

    /**
     * 判断今天是否在课程时间内
     *
     * @param course
     * @return
     */
    @Override
    public Boolean isExpireToday(Course course) {
        List<LocalDateTime> dateList = parseTime(course.getCourseTime(), "--", "yyyy-MM-dd");
        LocalDateTime now = LocalDateTime.now();

        return (now.isAfter(dateList.get(0)) && now.isBefore(dateList.get(1)));
    }

    /**
     * 按指定格式拆分返回时间
     *
     * @param stringTime
     * @param splitMethod
     * @param dateTimeFormat
     * @return
     */
    @Override
    public List<LocalDateTime> parseTime(String stringTime, String splitMethod, String dateTimeFormat) {
        return Arrays.stream(stringTime.split(splitMethod))
                .map(s -> {
                    try {
                        LocalDate date = LocalDate.parse(s, DateTimeFormatter.ofPattern(dateTimeFormat));
                        return LocalDateTime.of(date, LocalTime.now());
                    } catch (Exception e) {
                        LocalTime time = LocalTime.parse(s, DateTimeFormatter.ofPattern(dateTimeFormat));
                        return LocalDateTime.of(LocalDate.now(), time);
                    }

                })
                .toList();
    }
}
